package hu.mapro.gwtui.server.data;

import hu.mapro.gwtui.client.data.SortField;
import hu.mapro.gwtui.server.DataUtils;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Function;

public class DaoBase<T> implements DaoMethods<T> {

	protected Class<T> domainClass;
	protected Function<? super T, ?> keyProvider;
	
	public DaoBase(
			Class<T> domainClass,
			Function<? super T, ?> keyProvider
	) {
		super();
		this.domainClass = domainClass;
		this.keyProvider = keyProvider;
	}

	@PersistenceContext
	protected EntityManager entityManager;
	
	@Override
	public List<T> list(int firstResult, int maxResults,
			List<SortField> sortFields) {
		return DataUtils.list(entityManager, domainClass, firstResult, maxResults, sortFields);
	}

	@Override
	public Long count() {
		return DataUtils.count(entityManager, domainClass);
	}

	@Override
    @Transactional
	public void persist(T object) {
		entityManager.persist(object);
	}

	@Override
	@Transactional
	public void remove(T object) {
        if (this.entityManager.contains(object)) {
            this.entityManager.remove(object);
        } else {
            T attached = entityManager.find(domainClass, keyProvider.apply(object));
            this.entityManager.remove(attached);
        }	
    }

	@Override
    @Transactional
    public T merge(T object) {
        T merged = this.entityManager.merge(object);
        this.entityManager.flush();
        return merged;
    }
	
	
	@Override
	public List<T> list() {
		return DataUtils.list(entityManager, domainClass);
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	
}
